<template>
    <div class="create-container">
        <AtjHeader></AtjHeader>

        <div class="create-content">
            <!-- 标题输入 -->
            <div class="title-input">
                <input 
                    type="text" 
                    v-model="articleData.title"
                    placeholder="请输入文章标题..."
                    maxlength="255"
                    @input="validateTitle"
                >
                <span class="title-length">{{ articleData.title.length }}/255</span>
            </div>

            <!-- 描述输入 -->
            <div class="description-input">
                <textarea 
                    v-model="articleData.description"
                    placeholder="请输入文章描述..."
                    maxlength="500"
                    rows="3"
                ></textarea>
            </div>

            <!-- 分类选择 -->
            <div class="article-meta">
                <!-- 分类选择 -->
                <div class="custom-select" :class="{ active: isCategoryOpen }">
                    <div class="select-trigger" @click="toggleCategory">
                        <span :class="{ placeholder: !articleData.category_id }">
                            {{ selectedCategory?.name || '选择分类' }}
                        </span>
                        <span class="select-arrow"></span>
                    </div>
                    <div class="select-options" v-show="isCategoryOpen">
                        <div 
                            v-for="category in categories" 
                            :key="category.id"
                            class="option"
                            :class="{ selected: category.id === articleData.category_id }"
                            @click="selectCategory(category)"
                        >
                            <span class="option-icon">{{ category.icon || '📁' }}</span>
                            <span class="option-name">{{ category.name }}</span>
                        </div>
                    </div>
                </div>

                <!-- 标签选择 -->
                <div class="tags-input">
                    <span 
                        v-for="tag in selectedTags" 
                        :key="tag.id"
                        class="tag"
                    >
                        {{ tag.name }}
                        <span class="remove-tag" @click="removeTag(tag)">×</span>
                    </span>
                    <div class="custom-select" :class="{ active: isTagOpen }">
                        <div class="select-trigger" @click="toggleTag">
                            <span class="placeholder">选择标签</span>
                            <span class="select-arrow"></span>
                        </div>
                        <div class="select-options" v-show="isTagOpen">
                            <div 
                                v-for="tag in availableTags" 
                                :key="tag.id"
                                class="option"
                                @click="selectTag(tag)"
                            >
                                <span class="option-icon">#</span>
                                <span class="option-name">{{ tag.name }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 缩略图上传 -->
            <div class="thumbnail-upload">
                <input 
                    type="text" 
                    v-model="articleData.thumbnail_url"
                    placeholder="输入缩略图URL（可选）"
                >
            </div>

            <!-- 内容编辑器 -->
            <div class="editor-container">
                <CustomEditor
                    v-model="articleData.content"
                    placeholder="请输入文章内容..."
                    @change="handleEditorChange"
                />
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
                <button 
                    class="save-draft"
                    @click="saveAsDraft"
                    :disabled="!isValid || saving"
                >
                    保存草稿
                </button>
                <button 
                    class="publish"
                    @click="publish"
                    :disabled="!isValid || saving"
                >
                    发布文章
                </button>
            </div>
        </div>
    </div>
    <!-- 创作按钮组 -->
    <div class="floating-create-group" :class="{ active: isMenuOpen }">
        <div class="create-menu" v-show="isMenuOpen">
            <div class="menu-item" @click="goToCreate('article')">
                <span class="item-icon">📝</span>
                <span class="item-text">写文章</span>
            </div>
            <div class="menu-item" @click="goToCreate('thought')">
                <span class="item-icon">💭</span>
                <span class="item-text">写随笔</span>
            </div>
            <div class="menu-item" @click="goToCreate('question')">
                <span class="item-icon">❓</span>
                <span class="item-text">提问题</span>
            </div>
        </div>
        <div class="floating-create-button" @click="toggleMenu" :title="isMenuOpen ? '关闭' : '开始创作'">
            <span class="create-icon" :class="{ 'rotate': isMenuOpen }">✍️</span>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import CustomEditor from '@/components/CustomEditor.vue'
import AtjHeader from '@/components/AtjHeader.vue'
import { articleApi } from '@/api/article'
import { categoryApi } from '@/api/category'
import { tagApi } from '@/api/tag'

const router = useRouter()
const isMenuOpen = ref(false)

// 数据接口定义
interface ArticleData {
    title: string;
    content: string;
    description: string;
    thumbnail_url: string;
    author_id: number;  // 从用户状态获取
    category_id: number | null;
    status: 'draft' | 'published' | 'archived';
}
interface Category {
    id: number;
    name: string;
    icon?: string;
}

interface Tag {
    id: number;
    name: string;
}
const saving = ref(false)
const selectedTagId = ref<number | ''>('')
const selectedTags = ref<Tag[]>([])
const categories = ref<Category[]>([])
const allTags = ref<Tag[]>([])
const isCategoryOpen = ref(false)
const isTagOpen = ref(false)

// 文章数据
const articleData = ref<ArticleData>({
    title: '',
    content: '',
    description: '',
    thumbnail_url: '',
    author_id: 1, // 应该从用户状态获取
    category_id: null,
    status: 'draft'
})

// 获取可用标签（排除已选择的）
const availableTags = computed(() => {
    return allTags.value.filter(tag => 
        !selectedTags.value.find(selected => selected.id === tag.id)
    )
})

// 验证标题
const validateTitle = () => {
    if (articleData.value.title.length > 255) {
        articleData.value.title = articleData.value.title.slice(0, 255)
    }
}

// 添加标签
const addTag = () => {
    if (selectedTagId.value) {
        const tag = allTags.value.find(t => t.id === selectedTagId.value)
        if (tag && !selectedTags.value.find(t => t.id === tag.id)) {
            selectedTags.value.push(tag)
        }
        selectedTagId.value = ''
    }
}
// 移除标签
const removeTag = (tag: Tag) => {
    selectedTags.value = selectedTags.value.filter(t => t.id !== tag.id)
}

// 表单验证
const isValid = computed(() => {
    return articleData.value.title.trim() && 
           articleData.value.content.trim() && 
           articleData.value.category_id
})
// 获取分类和标签数据
const fetchCategoriesAndTags = async () => {
    try {
        const [categoriesResponse, tagsResponse] = await Promise.all([
            categoryApi.getCategories(),
            tagApi.getTags()
        ])
        categories.value = categoriesResponse
        allTags.value = tagsResponse
    } catch (error) {
        console.error('Error fetching categories and tags:', error)
    }
}
// 切换分类下拉框
const toggleCategory = () => {
    isCategoryOpen.value = !isCategoryOpen.value
    isTagOpen.value = false  // 关闭另一个下拉框
}

// 切换标签下拉框
const toggleTag = () => {
    isTagOpen.value = !isTagOpen.value
    isCategoryOpen.value = false  // 关闭另一个下拉框
}

// 选择分类
const selectCategory = (category: Category) => {
    articleData.value.category_id = category.id
    isCategoryOpen.value = false
}

// 选择标签
const selectTag = (tag: Tag) => {
    if (!selectedTags.value.find(t => t.id === tag.id)) {
        selectedTags.value.push(tag)
    }
    isTagOpen.value = false
}

// 计算当前选中的分类
const selectedCategory = computed(() => 
    categories.value.find(c => c.id === articleData.value.category_id)
)
// 保存文章
const saveArticle = async (status: 'draft' | 'published') => {
    try {
        saving.value = true
        articleData.value.status = status

        // 准备要发送的数据
        const articlePayload = {
            ...articleData.value,
            tags: selectedTags.value.map(tag => tag.name)
        }
        const id = await articleApi.createArticle(articlePayload)
        router.push({ path: '/createdsuccess', query: { id: id.articleId } })
    } catch (error) {
        console.error('Error saving article:', error)
    } finally {
        saving.value = false
    }
}
// 保存草稿
const saveAsDraft = () => saveArticle('draft')

// 发布文章
const publish = () => saveArticle('published')
const toggleMenu = () => {
    isMenuOpen.value = !isMenuOpen.value
}

// 初始化
onMounted(() => {
    fetchCategoriesAndTags()
    document.addEventListener('click', (e) => {
        const target = e.target as HTMLElement
        if (!target.closest('.custom-select')) {
            isCategoryOpen.value = false
            isTagOpen.value = false
        }
    })
})
</script>

<style lang="less" scoped>
.create-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.create-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 24px;
    margin-top: 20px;
}

.title-input {
    position: relative;
    margin-bottom: 20px;

    input {
        width: 100%;
        padding: 16px;
        font-size: 24px;
        border: none;
        border-bottom: 2px solid #eee;
        outline: none;
        transition: border-color 0.3s;

        &:focus {
            border-color: var(--primary-color);
        }
    }

    .title-length {
        position: absolute;
        right: 16px;
        bottom: 16px;
        color: #999;
        font-size: 12px;
    }
}

.article-meta {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    .custom-select {
        position: relative;
        min-width: 120px;
        user-select: none;

        .select-trigger {
            padding: 8px 32px 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            background: white;
            cursor: pointer;
            position: relative;
            transition: all 0.3s ease;
            font-size: 14px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 8px;

            .placeholder {
                color: #999;
            }

            .select-arrow {
                position: absolute;
                right: 12px;
                top: 50%;
                transform: translateY(-50%);
                width: 10px;
                height: 10px;
                border-right: 2px solid #666;
                border-bottom: 2px solid #666;
                transform: translateY(-50%) rotate(45deg);
                transition: transform 0.3s ease;
            }
        }

        &.active {
            .select-trigger {
                border-color: var(--primary-color);
                box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.1);

                .select-arrow {
                    transform: translateY(-50%) rotate(-135deg);
                }
            }
        }

        .select-options {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            margin-top: 4px;
            background: white;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            max-height: 200px;
            overflow-y: auto;
            animation: slideDown 0.2s ease;

            .option {
                padding: 8px 12px;
                cursor: pointer;
                display: flex;
                align-items: center;
                gap: 8px;
                transition: all 0.2s ease;

                &:hover {
                    background: #f0f7ff;
                    color: var(--primary-color);
                }

                &.selected {
                    background: #e6f0ff;
                    color: var(--primary-color);
                }

                .option-icon {
                    font-size: 16px;
                    opacity: 0.8;
                }

                .option-name {
                    flex: 1;
                    font-size: 14px;
                }
            }
        }
    }
    /* 标签输入样式 */
    .tags-input {
        display: flex;
        flex-wrap: wrap; /* 允许换行 */
        gap: 8px; /* 标签之间的间距 */
        margin-bottom: 20px; /* 标签输入的底部间距 */
        /* 单个标签样式 */
        .tag {
            background: #92c7ed; /* 标签背景色 */
            color: #ffffff; /* 标签文字颜色 */
            padding: 6px 12px; /* 标签内边距 */
            border-radius: 4px; /* 标签圆角 */
            display: flex; /* 使用 flexbox 布局 */
            align-items: center; /* 垂直居中 */
        }
        /* 移除标签的样式 */
        .remove-tag {
            margin-left: 8px; /* 移除按钮与标签的间距 */
            cursor: pointer; /* 鼠标悬停时显示为可点击 */
            color: #ff4d4f; /* 移除按钮颜色 */
            font-weight: bold; /* 加粗 */
        }
        /* 移除按钮悬停效果 */
        .remove-tag:hover {
            color: #ff7875; /* 悬停时颜色变化 */
        }
    }
    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    // 美化滚动条
    .select-options {
        &::-webkit-scrollbar {
            width: 6px;
        }

        &::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }

        &::-webkit-scrollbar-thumb {
            background: #ccc;
            border-radius: 3px;

            &:hover {
                background: #999;
            }
        }
    }
    
}

.editor-container {
    margin-bottom: 20px;

    textarea {
        width: 100%;
        padding: 16px;
        border: 1px solid #ddd;
        border-radius: 4px;
        outline: none;
        resize: vertical;
        min-height: 400px;
        font-size: 16px;
        line-height: 1.6;

        &:focus {
            border-color: var(--primary-color);
        }
    }
}

.action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 16px;

    button {
        padding: 10px 24px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        transition: all 0.3s;

        &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
    }

    .save-draft {
        background: #f0f0f0;
        color: #666;

        &:hover:not(:disabled) {
            background: #e0e0e0;
        }
    }

    .publish {
        background: var(--primary-color);
        color: white;

        &:hover:not(:disabled) {
            background: darken(#1a73e8, 10%);
        }
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .create-container {
        padding: 10px;
    }

    .article-meta {
        flex-direction: column;
    }

    .action-buttons {
        flex-direction: column;
        
        button {
            width: 100%;
        }
    }
}
.floating-create-group {
    position: fixed;
    right: 40px;
    bottom: 40px;
    z-index: 1000;
}

.create-menu {
    position: absolute;
    bottom: 80px;
    right: 0;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    padding: 8px;
    animation: slideUp 0.3s ease;
}

.menu-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    cursor: pointer;
    border-radius: 8px;
    transition: all 0.2s ease;
    white-space: nowrap;

    &:hover {
        background: rgba(26, 115, 232, 0.1);
        color: var(--primary-color);
    }

    .item-icon {
        font-size: 18px;
    }

    .item-text {
        font-size: 14px;
        font-weight: 500;
    }
}

.floating-create-button {
    width: 56px;
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    color: white;
    border-radius: 50%;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
    }

    .create-icon {
        font-size: 24px;
        transition: transform 0.3s ease;

        &.rotate {
            transform: rotate(45deg);
        }
    }
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .floating-create-group {
        right: 20px;
        bottom: 20px;
    }

    .floating-create-button {
        width: 48px;
        height: 48px;
    }
}
// 添加新样式
.description-input {
    margin-bottom: 20px;

    textarea {
        width: 100%;
        padding: 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        resize: vertical;
        outline: none;

        &:focus {
            border-color: var(--primary-color);
        }
    }
}

.thumbnail-upload {
    margin-bottom: 20px;

    input {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        outline: none;

        &:focus {
            border-color: var(--primary-color);
        }
    }
}

.tag-select {
    padding: 4px 8px;
    border: none;
    outline: none;
    background: transparent;
    color: var(--primary-color);
    cursor: pointer;

    &:focus {
        background: #f5f5f5;
    }
}
</style>